package udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

/**
 * Created with IntelliJ IDEA
 * Description：创建UDP服务器
 * User：chenshu
 * Date：2023-11-23
 * Time：10:02
 */
public class EchoServer {
    //打开一个socket文件
    private DatagramSocket socket = null;

    public EchoServer(int port) throws SocketException {
        //给socket文件分配端口号
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            //1.读取客户端发来的请求
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(requestPacket);

            //2.解析请求
            String request = new String(requestPacket.getData(), 0, requestPacket.getLength(), "UTF-8");
            //3.根据请求响应
            String response = process(request);

            //4.把响应分装成数据报
            DatagramPacket responsePacket = new DatagramPacket(
                    response.getBytes(StandardCharsets.UTF_8),
                    response.getBytes().length,
                    requestPacket.getSocketAddress());

            //5.发送响应
            socket.send(responsePacket);
            System.out.printf("[%s:%d]request：%s, response：%s\n", responsePacket.getAddress(), responsePacket.getPort(), request, response);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        EchoServer echoClient = new EchoServer(8080);
        echoClient.start();
    }
}
